package http

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/baker-yuan-connect/botgo/dto"
	"io/ioutil"
	"log"
	"net/http"
)






// SendMessage 发送消息
// https://bot.q.qq.com/wiki/develop/api/openapi/message/post_messages.html
func SendMessage(channelId string, msgId string, message string, authToken string) {
	log.Printf("sendMessage: channelId=%s,msgId=%s,message=%s,authToken=%s", channelId, msgId, message, authToken)
	if len(message) == 0 || len(channelId) == 0 || len(msgId) == 0 || len(authToken) == 0 {
		log.Println("SendMessage 参数校验失败")
		return
	}

	// 1、构建请求地址
	url := "https://sandbox.api.sgroup.qq.com/channels/" + channelId + "/messages"

	// 2、构建请求体
	msg := &dto.MessageToCreate{
		Content: message,
		MsgID:   msgId,
	}
	body, _ := json.Marshal(&msg)

	// 3、构建客户端
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, bytes.NewReader(body))

	// 4、增加header选项
	req.Header.Add("Authorization", "Bot "+authToken)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36")

	// 5、发送请求
	resp, _ := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}
	// 关闭资源
	defer resp.Body.Close()

	// 解析返回值
	resBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	log.Println("SendMessage 返回值：", string(resBody))
}
